package com.starblink.discover.util;

import android.content.pm.ActivityInfo;
import android.graphics.Rect;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.ViewParent;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.Lifecycle;
import androidx.recyclerview.widget.RecyclerView;

import com.shuyu.gsyvideoplayer.video.base.GSYBaseVideoPlayer;
import com.starblink.android.common.view.post.NavPrepareView;
import com.starblink.product.controller.VideoRenderViewFactory;
import com.starblink.rocketreserver.fragment.PostF;
import com.starblink.video.controller.BaseVideoController;
import com.starblink.video.player.BaseVideoView;
import com.starblink.video.player.VideoView;
import com.starblink.video.util.VideoUtils;
import com.starblink.videocache.cache.PreloadManager;

/**
 * 计算滑动，自动播放的帮助类
 * Created by guoshuyu on 2017/11/2.
 */

public class ScrollCalculatorHelper2 {

    private int firstVisible = 0;
    private int lastVisible = 0;
    private int visibleCount = 0;
    private int playId;
    private int rangeTop;
    private int rangeBottom;
    private PlayRunnable runnable;

    private Handler playHandler = new Handler();
    PreloadManager mPreloadManager;
    protected VideoView mVideoView;
    protected BaseVideoController mController;

    /**
     * 当前播放的位置
     */
    protected int mCurPos = -1;
    /**
     * 上次播放的位置，用于页面切回来之后恢复播放
     */
    protected int mLastPos = mCurPos;
    FragmentActivity context;

    public ScrollCalculatorHelper2(FragmentActivity context, Lifecycle lifecycle, int playId, int rangeTop, int rangeBottom) {
        this.context = context;
        this.playId = playId;
        this.rangeTop = rangeTop;
        this.rangeBottom = rangeBottom;
        mPreloadManager = PreloadManager.getInstance(context);
        mVideoView = new VideoView(context);
        mVideoView.setOnStateChangeListener(new VideoView.SimpleOnStateChangeListener() {
            @Override
            public void onPlayStateChanged(int playState) {
                //监听VideoViewManager释放，重置状态
                if (playState == VideoView.STATE_IDLE) {
                    removeViewFormParent(mVideoView);
                    mLastPos = mCurPos;
                    mCurPos = -1;
                }
            }
        });
        mController = new BaseVideoController(context) {
            @Override
            protected int getLayoutId() {
                return 0;
            }
        };
        mVideoView.setVideoController(mController);
        mVideoView.setLooping(true);
        mVideoView.setRenderViewFactory(VideoRenderViewFactory.create());
        mVideoView.setLifecycle(lifecycle);
        mVideoView.setMute(true);
    }

    public void onScrollStateChanged(RecyclerView view, int scrollState) {
        switch (scrollState) {
            case RecyclerView.SCROLL_STATE_IDLE:
                playVideo(view);
                break;
        }
    }

    public void onScroll(RecyclerView view, int firstVisibleItem, int lastVisibleItem, int visibleItemCount) {
        if (firstVisible == firstVisibleItem) {
            return;
        }
        firstVisible = firstVisibleItem;
        lastVisible = lastVisibleItem;
        visibleCount = visibleItemCount;
    }


    void playVideo(RecyclerView view) {

        if (view == null) {
            return;
        }

        RecyclerView.LayoutManager layoutManager = view.getLayoutManager();

//        GSYBaseVideoPlayer gsyBaseVideoPlayer = null;

        boolean needPlay = false;

        for (int i = 0; i < visibleCount; i++) {
            if (layoutManager.getChildAt(i) != null && layoutManager.getChildAt(i).findViewById(playId) != null) {
                View itemView = layoutManager.getChildAt(i);
                FrameLayout player = itemView.findViewById(playId);
                NavPrepareView prepare_view = itemView.findViewById(com.starblink.android.common.R.id.prepare_view);
                Rect rect = new Rect();
                player.getLocalVisibleRect(rect);
                int height = player.getHeight();
                //说明第一个完全可视
                if (rect.top == 0 && rect.bottom == height && height > 0) {
//                    gsyBaseVideoPlayer = player;
//                    if ((player.getCurrentPlayer().getCurrentState() == GSYBaseVideoPlayer.CURRENT_STATE_NORMAL
//                            || player.getCurrentPlayer().getCurrentState() == GSYBaseVideoPlayer.CURRENT_STATE_ERROR)) {
//                        needPlay = true;
//                    }
                    PostF tiktokBean = (PostF) itemView.getTag();
                    if (tiktokBean != null) {
                        mVideoView.release();
                        VideoUtils.removeViewFormParent(mVideoView);
                        if (tiktokBean.getPictures() != null && tiktokBean.getPictures().size() > 0) {
                            String playUrl = mPreloadManager.getPlayUrl(
                                    tiktokBean.getPictures().get(0).getPictureF().getPicUrl()
                            );
                            mVideoView.setUrl(playUrl);
                            //请点进去看isDissociate的解释
                            mController.addControlComponent(prepare_view, true);
                            player.addView(mVideoView, 0);
                            Log.e("ScrollCalculatorHelper2", "=====" + mVideoView.getCurrentPlayState());
                            if ((mVideoView.getCurrentPlayState() == BaseVideoView.STATE_IDLE
                                    || mVideoView.getCurrentPlayState() == BaseVideoView.STATE_ERROR)) {
                                mVideoView.start();
                            }
                            mCurPos = i;

                            needPlay = true;
                        }
                    }
                    break;
                }

            }

        }
//        if (mVideoView != null && needPlay) {
//            if (runnable != null) {
//                GSYBaseVideoPlayer tmpPlayer = runnable.mVideoView;
//                playHandler.removeCallbacks(runnable);
//                runnable = null;
//                if (tmpPlayer == gsyBaseVideoPlayer) {
//                    return;
//                }
//            }
//            runnable = new PlayRunnable(gsyBaseVideoPlayer);
//            //降低频率
//            playHandler.postDelayed(runnable, 200);
//        }

        view.addOnChildAttachStateChangeListener(new RecyclerView.OnChildAttachStateChangeListener() {
            @Override
            public void onChildViewAttachedToWindow(@NonNull View view) {

            }

            @Override
            public void onChildViewDetachedFromWindow(@NonNull View view) {
                FrameLayout playerContainer = view.findViewById(playId);
                if (playerContainer != null) {
                    View v = playerContainer.getChildAt(0);
                    if (v != null && v == mVideoView && !mVideoView.isFullScreen()) {
                        releaseVideoView();
                    }
                }
            }
        });

    }

    private void releaseVideoView() {
        mVideoView.release();
        if (mVideoView.isFullScreen()) {
            mVideoView.stopFullScreen();
        }
        if (context.getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
            context.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
        mCurPos = -1;
    }

    /**
     * 将View从父控件中移除
     */
    public static void removeViewFormParent(View v) {
        if (v == null) return;
        ViewParent parent = v.getParent();
        if (parent instanceof FrameLayout) {
            ((FrameLayout) parent).removeView(v);
        }
    }

    private class PlayRunnable implements Runnable {

        GSYBaseVideoPlayer gsyBaseVideoPlayer;

        public PlayRunnable(GSYBaseVideoPlayer gsyBaseVideoPlayer) {
            this.gsyBaseVideoPlayer = gsyBaseVideoPlayer;
        }

        @Override
        public void run() {
            boolean inPosition = false;
            //如果未播放，需要播放
            if (gsyBaseVideoPlayer != null) {
                int[] screenPosition = new int[2];
                gsyBaseVideoPlayer.getLocationOnScreen(screenPosition);
                int halfHeight = gsyBaseVideoPlayer.getHeight() / 2;
                int rangePosition = screenPosition[1] + halfHeight;
                //中心点在播放区域内
                if (rangePosition >= rangeTop && rangePosition <= rangeBottom) {
                    inPosition = true;
                }
                if (inPosition) {
                    mVideoView.start();
//                    startPlayLogic(gsyBaseVideoPlayer, gsyBaseVideoPlayer.getContext());
                    //gsyBaseVideoPlayer.startPlayLogic();
                }
            }
        }
    }


}
